<template>
  <div class="health-records">
    <div class="page-header">
      <h2 class="page-title">健康数据记录</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加记录
      </el-button>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="老人姓名">
          <el-select v-model="searchForm.elderlyId" placeholder="请选择老人" clearable filterable style="width: 200px">
            <el-option
              v-for="elderly in elderlyOptions"
              :key="elderly.id"
              :label="elderly.name"
              :value="elderly.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="记录类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="血压" value="blood_pressure" />
            <el-option label="体温" value="temperature" />
            <el-option label="心率" value="heart_rate" />
            <el-option label="血糖" value="blood_sugar" />
            <el-option label="体重" value="weight" />
          </el-select>
        </el-form-item>
        <el-form-item label="记录日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table :data="recordsList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="elderlyName" label="老人姓名" />
        <el-table-column prop="type" label="记录类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="数值" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="recordTime" label="记录时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.recordTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="recordedByName" label="记录人员" width="120" show-overflow-tooltip />
        <el-table-column prop="notes" label="备注" show-overflow-tooltip />
        <el-table-column prop="suggestions" label="健康建议" show-overflow-tooltip width="150">
          <template #default="{ row }">
            <span v-if="row.suggestions" style="color: #409EFF;">{{ row.suggestions }}</span>
            <span v-else style="color: #909399;">无</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="老人" prop="elderlyId">
          <el-select v-model="formData.elderlyId" placeholder="请选择老人" filterable>
            <el-option
              v-for="elderly in elderlyOptions"
              :key="elderly.id"
              :label="elderly.name"
              :value="elderly.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="记录类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择记录类型" @change="handleTypeChange">
            <el-option label="血压" value="blood_pressure" />
            <el-option label="体温" value="temperature" />
            <el-option label="心率" value="heart_rate" />
            <el-option label="血糖" value="blood_sugar" />
            <el-option label="体重" value="weight" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="formData.type === 'blood_pressure'" label="血压值" prop="bloodPressure">
          <el-row :gutter="10">
            <el-col :span="11">
              <el-input-number v-model="formData.systolic" :min="50" :max="300" placeholder="收缩压" />
            </el-col>
            <el-col :span="2" style="text-align: center; line-height: 32px;">/</el-col>
            <el-col :span="11">
              <el-input-number v-model="formData.diastolic" :min="30" :max="200" placeholder="舒张压" />
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-form-item v-else label="数值" prop="value">
          <el-input-number v-model="formData.value" :min="0" :precision="getPrecision()" />
        </el-form-item>
        
        <el-form-item label="单位">
          <el-input v-model="formData.unit" readonly />
        </el-form-item>
        
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker
            v-model="formData.recordTime"
            type="datetime"
            placeholder="选择记录时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="记录人员" prop="recordedBy">
          <el-select v-model="formData.recordedBy" placeholder="请选择记录人员" filterable clearable>
            <el-option
              v-for="staff in staffOptions"
              :key="staff.id"
              :label="staff.name"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input v-model="formData.notes" type="textarea" rows="3" />
        </el-form-item>
        
        <el-form-item label="健康建议">
          <el-input v-model="formData.suggestions" type="textarea" rows="3" placeholder="请输入健康建议" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="健康记录详情" width="500px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="编号">{{ viewData.id }}</el-descriptions-item>
        <el-descriptions-item label="老人姓名">{{ viewData.elderlyName }}</el-descriptions-item>
        <el-descriptions-item label="记录类型">
          <el-tag :type="getTypeColor(viewData.type)">
            {{ getTypeLabel(viewData.type) }}
          </el-tag>
        </el-descriptions-item>
        
        <!-- 血压类型特殊显示 -->
        <template v-if="viewData.type === 'blood_pressure'">
          <el-descriptions-item label="收缩压">{{ viewData.systolicPressure || 0 }} mmHg</el-descriptions-item>
          <el-descriptions-item label="舒张压">{{ viewData.diastolicPressure || 0 }} mmHg</el-descriptions-item>
          <el-descriptions-item label="血压值">{{ viewData.value }}</el-descriptions-item>
        </template>
        
        <!-- 其他类型正常显示 -->
        <el-descriptions-item v-else label="数值">{{ viewData.value }} {{ viewData.unit }}</el-descriptions-item>
        
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(viewData.status)">
            {{ getStatusLabel(viewData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="记录时间">{{ formatDateTime(viewData.recordTime) }}</el-descriptions-item>
        <el-descriptions-item label="记录人员">{{ viewData.recordedByName || '未指定' }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ viewData.notes || '无' }}</el-descriptions-item>
        <el-descriptions-item label="健康建议" v-if="viewData.suggestions">
          <div style="color: #409EFF;">{{ viewData.suggestions }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const recordsList = ref<any[]>([])
const elderlyOptions = ref<any[]>([])
const staffOptions = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  elderlyId: '',
  type: '',
  dateRange: []
})

// 弹窗相关
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const formRef = ref()
const formData = reactive({
  id: null,
  elderlyId: '',
  type: '',
  value: 0 as any,
  systolic: 0,  // 收缩压
  diastolic: 0, // 舒张压
  unit: '',
  recordTime: new Date(),
  recordedBy: '', // 记录人员ID
  notes: '',
  suggestions: ''
})

// 查看数据
const viewData = ref<any>({})

// 类型单位映射
const typeUnitMap: { [key: string]: string } = {
  blood_pressure: 'mmHg',
  temperature: '°C',
  heart_rate: '次/分',
  blood_sugar: 'mmol/L',
  weight: 'kg'
}

// 表单验证规则
const formRules = {
  elderlyId: [
    { required: true, message: '请选择老人', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择记录类型', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入数值', trigger: 'blur' }
  ],
  recordTime: [
    { required: true, message: '请选择记录时间', trigger: 'change' }
  ]
}

// API 基础URL
const API_BASE_URL = 'http://localhost:8080/api'

// 获取类型标签
const getTypeLabel = (type: string) => {
  const typeMap: { [key: string]: string } = {
    blood_pressure: '血压',
    temperature: '体温',
    heart_rate: '心率',
    blood_sugar: '血糖',
    weight: '体重'
  }
  return typeMap[type] || type
}

// 获取类型颜色
const getTypeColor = (type: string) => {
  const colorMap: { [key: string]: string } = {
    blood_pressure: 'danger',
    temperature: 'warning',
    heart_rate: 'success',
    blood_sugar: 'info',
    weight: 'primary'
  }
  return colorMap[type] || 'default'
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const statusMap: { [key: string]: string } = {
    normal: '正常',
    NORMAL: '正常',
    low: '偏低',
    LOW: '偏低',
    high: '偏高',
    HIGH: '偏高',
    abnormal: '异常',
    ABNORMAL: '异常'
  }
  return statusMap[status] || status
}

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: { [key: string]: string } = {
    normal: 'success',
    NORMAL: 'success',
    low: 'warning',
    LOW: 'warning',
    high: 'danger',
    HIGH: 'danger',
    abnormal: 'danger',
    ABNORMAL: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取精度
const getPrecision = () => {
  if (formData.type === 'blood_sugar') return 1
  if (formData.type === 'temperature') return 1
  return 0
}

// 处理类型变化
const handleTypeChange = (type: string) => {
  formData.unit = typeUnitMap[type] || ''
  formData.value = 0
  formData.systolic = 0
  formData.diastolic = 0
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', (currentPage.value - 1).toString())
    params.append('size', pageSize.value.toString())
    
    // 添加搜索条件
    if (searchForm.elderlyId) {
      params.append('elderlyId', searchForm.elderlyId.toString())
    }
    if (searchForm.type) {
      params.append('recordType', searchForm.type)
    }
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.append('startTime', (searchForm.dateRange[0] as Date).toISOString())
      params.append('endTime', (searchForm.dateRange[1] as Date).toISOString())
    }
    
    const response = await fetch(`${API_BASE_URL}/health-records?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error('获取健康记录失败')
    }
    
    const result = await response.json()
    if (result.code === 200) {
      // 处理数据，添加老人姓名和完善字段映射
      const recordsWithNames = await Promise.all(result.data.content.map(async (record: any) => {
        const elderlyName = await getElderlyName(record.elderlyId)
        const recordedByName = await getStaffName(record.recordedBy)
        
        // 调试：打印原始数据
        if (record.recordType === 'blood_pressure') {
          console.log('血压记录原始数据:', record)
        }
        
        // 处理不同类型的数值显示
        let displayValue = ''
        if (record.recordType === 'blood_pressure') {
          displayValue = `${record.systolicPressure || 0}/${record.diastolicPressure || 0}`
        } else {
          displayValue = record.value?.toString() || '0'
        }
        
        return {
          id: record.id,
          elderlyId: record.elderlyId,
          elderlyName,
          type: record.recordType,
          value: displayValue,
          unit: record.unit || getDefaultUnit(record.recordType),
          status: record.status || 'normal',
          recordTime: record.recordTime,
          notes: record.notes || '',
          suggestions: record.suggestions || '',
          recordedBy: record.recordedBy,
          recordedByName,
          // 原始数据保留
          systolicPressure: record.systolicPressure,
          diastolicPressure: record.diastolicPressure
        }
      }))
      
      recordsList.value = recordsWithNames
      total.value = result.data.totalElements
    } else {
      ElMessage.error(result.message || '获取健康记录失败')
    }
  } catch (error) {
    console.error('加载健康记录失败:', error)
    ElMessage.error('加载健康记录失败')
  } finally {
    loading.value = false
  }
}

// 获取老人姓名
const getElderlyName = async (elderlyId: number) => {
  try {
    const response = await fetch(`${API_BASE_URL}/elderly/${elderlyId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        return result.data.name
      }
    }
    return `老人${elderlyId}`
  } catch (error) {
    return `老人${elderlyId}`
  }
}

// 获取员工姓名
const getStaffName = async (staffId: number | null) => {
  if (!staffId) return '未指定'
  
  try {
    const response = await fetch(`${API_BASE_URL}/staff/${staffId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        return result.data.name
      }
    }
    return `员工${staffId}`
  } catch (error) {
    return `员工${staffId}`
  }
}

// 加载老人选项
const loadElderlyOptions = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/elderly?page=0&size=100`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        elderlyOptions.value = result.data.content.map((elderly: any) => ({
          id: elderly.id,
          name: elderly.name
        }))
      }
    }
  } catch (error) {
    console.error('加载老人选项失败:', error)
  }
}

// 加载员工选项
const loadStaffOptions = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/staff?page=0&size=100`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        staffOptions.value = result.data.content.map((staff: any) => ({
          id: staff.id,
          name: staff.name
        }))
      }
    }
  } catch (error) {
    console.error('加载员工选项失败:', error)
  }
}

// 搜索
const handleSearch = async () => {
  currentPage.value = 1 // 重置到第一页
  await loadData()
}

// 重置搜索
const resetSearch = async () => {
  Object.assign(searchForm, {
    elderlyId: '',
    type: '',
    dateRange: []
  })
  currentPage.value = 1
  await loadData()
}

// 添加
const handleAdd = () => {
  dialogTitle.value = '添加健康记录'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑健康记录'
  isEdit.value = true
  
  // 处理血压特殊情况 - 直接使用原始数据
  if (row.type === 'blood_pressure') {
    formData.systolic = row.systolicPressure || 0
    formData.diastolic = row.diastolicPressure || 0
  }
  
  Object.assign(formData, {
    ...row,
    recordTime: new Date(row.recordTime)
  })
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  viewData.value = row
  viewDialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await fetch(`${API_BASE_URL}/health-records/${row.id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error('删除失败')
    }
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('删除成功')
      await loadData()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除健康记录失败:', error)
      ElMessage.error('删除健康记录失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    // 准备提交数据
    const submitData: any = {
      elderlyId: formData.elderlyId,
      recordType: formData.type,
      unit: formData.unit,
      recordTime: formData.recordTime.toISOString(),
      recordedBy: formData.recordedBy || null,
      notes: formData.notes || '',
      suggestions: formData.suggestions || ''
    }
    
    // 处理不同类型的数值
    if (formData.type === 'blood_pressure') {
      submitData.systolicPressure = formData.systolic
      submitData.diastolicPressure = formData.diastolic
      submitData.value = null
    } else {
      submitData.value = parseFloat(formData.value.toString())
      submitData.systolicPressure = null
      submitData.diastolicPressure = null
    }
    
    let response
    if (isEdit.value) {
      // 更新
      response = await fetch(`${API_BASE_URL}/health-records/${formData.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(submitData)
      })
    } else {
      // 创建
      response = await fetch(`${API_BASE_URL}/health-records`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(submitData)
      })
    }
    
    if (!response.ok) {
      throw new Error(isEdit.value ? '更新失败' : '添加失败')
    }
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      dialogVisible.value = false
      await loadData()
    } else {
      ElMessage.error(result.message || (isEdit.value ? '更新失败' : '添加失败'))
    }
  } catch (error: any) {
    console.error('提交健康记录失败:', error)
    ElMessage.error(isEdit.value ? '更新健康记录失败' : '添加健康记录失败')
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: null,
    elderlyId: '',
    type: '',
    value: 0,
    systolic: 0,
    diastolic: 0,
    unit: '',
    recordTime: new Date(),
    recordedBy: '',
    notes: '',
    suggestions: ''
  })
}

// 分页
const handleSizeChange = async (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  await loadData()
}

const handleCurrentChange = async (val: number) => {
  currentPage.value = val
  await loadData()
}

// 获取默认单位
const getDefaultUnit = (recordType: string) => {
  const unitMap: { [key: string]: string } = {
    blood_pressure: 'mmHg',
    temperature: '°C',
    heart_rate: '次/分',
    blood_sugar: 'mmol/L',
    weight: 'kg'
  }
  return unitMap[recordType] || ''
}

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  loadElderlyOptions()
  loadStaffOptions()
  loadData()
})
</script>

<style scoped>
.health-records {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 